package com.kongchengji.zhanguafou.service;

import com.alibaba.fastjson.JSONObject;
import com.kongchengji.zhanguafou.constant.WxInfo;
import com.kongchengji.zhanguafou.dao.UserDAO;
import com.kongchengji.zhanguafou.domain.UserDO;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;

@Service
public class SubscribeService {
    @Autowired
    UserDAO userDAO;
    /**
     * 订阅事件,取消订阅处理
     * @param map 保存着微信发送过来的消息
     */
    public void subscribeEvent(Map<String,String> map){
        //1.首先获得用户的openId.
        String openId = map.get("FromUserName");
        //2.判断是订阅事件还是取消订阅事件。
        String event = map.get("Event");
        //3.如果是订阅事件，获取用户的信息列表，保存需要的用户数据
        if(event.equals("subscribe")){
            Map userInfo = getUserInfo(openId);
            UserDO userDO = new UserDO();
            userDO.setOpenId((String) userInfo.get("openid"));
            //判断是否是二次订阅
            if(userDAO.selectByPrimaryKey(userDO) != null){
                userDO.setSubscribe(1);
                userDAO.updateByPrimaryKeySelective(userDO);
                return;
            }
            userDO.setNickname((String) userInfo.get("nickname"));
            userDO.setHeadimgurl((String) userInfo.get("headimgurl"));
            userDO.setSubscribeTime((Integer) userInfo.get("subscribe_time"));
            userDO.setSubscribe((Integer) userInfo.get("subscribe"));
            //保存数据库
            userDAO.insertSelective(userDO);
        }else {
            //4.如果是取消订阅事件，将订阅标识改为0。
            UserDO userDO = new UserDO();
            userDO.setOpenId(openId);
            userDO.setSubscribe(0);
            userDAO.updateByPrimaryKeySelective(userDO);
        }

    }

    /**
     * 通过openId获取用户信息
     * @param openId 用于在个公众号的唯一标识
     * @return 将微信发送过来的消息解析并封装成map
     */
    private Map<String,String> getUserInfo(String openId){
        Map map;
        Request request = new Request.Builder()
                .url("https://api.weixin.qq.com/cgi-bin/user/info?access_token="+ WxInfo.accessToken.getToken()+"&openid="+openId+"&lang=zh_CN")
                .build();
        OkHttpClient client = new OkHttpClient();
        try {
            Response response = client.newCall(request).execute();
            String reply = response.body().string();
            map = JSONObject.parseObject(reply,Map.class);
            return map;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

